<template>
  <div class="layout-pd">
    <zh-space style="padding-top: 10px">
      <zh-card title="">
        <zh-form ref="roleForm" :model="state.queryParam">
          <zh-form-input prop="roleName" label="角色名称" placeholder="支持模糊查询" v-model="state.queryParam.roleName"></zh-form-input>
          <zh-form-select
              prop="roleType"
              label="角色类型"
              placeholder="单选"
              :options="state.dictData.roleType"
              v-model="state.queryParam.roleType"
          ></zh-form-select>
          <template v-if="state.advanced">
            <zh-form-select
                prop="status"
                label="状态"
                placeholder="单选"
                :options="state.statusData"
                v-model="state.queryParam.status"
            ></zh-form-select>
          </template>
          <zh-form-query v-model="state.advanced" :form-ref="roleForm" :table-ref="roleTable">
            <zh-button style="margin-left: 8px" button-type="add" @click="addRole"> 创建角色 </zh-button>
          </zh-form-query>
        </zh-form>
      </zh-card>
      <zh-table
          ref="roleTable"
          title=""
          :height="600"
          funcCode="role0001"
          :columns="state.tableColumn"
          :disabled="false"
          highlight-current-row
      >
        <template #status_edit="{ row }">
          <el-switch
              v-model="row.status"
              active-text="启用"
              inactive-text="禁用"
              active-value="1"
              inactive-value="0"
              inline-prompt
              size="large"
              :disabled="row.disabled"
              @change="onStatusChange(row)"
              :width="50"
          ></el-switch>
        </template>
        <template #fixed_default="{ row }">
          <zh-badge :status="flagMap[row.fixed].status" :text="flagMap[row.fixed].text" />
        </template>
        <template #operate_default="{ row }">
          <zh-button v-func:role0005  link  button-type="edit" @click="editRole(row)">编辑 </zh-button>
          <zh-button v-func:role0006 link button-type="del" @click="deleteRole(row)">删除 </zh-button>
          <zh-button v-func:role0012 link icon="ele-Calendar" type="primary" @click="openRoleRouterFuncModel(row)">菜单 </zh-button>
          <el-dropdown trigger="click" style="margin-left:10px;margin-top: 5px;">
            <a style=""
            >更多 <el-icon class="el-icon--right"> <arrow-down /> </el-icon
            ></a>
            <template #dropdown>
              <el-dropdown-menu>

                <div v-func:role0015>
                  <el-dropdown-item key="3" @click="openRoleOrgModel(row)">
                    <SvgIcon name="ele-EditPen" color="#e6a23c"/>
                    <span style="padding-left: 5px; color: #e6a23c">组织</span>
                  </el-dropdown-item>
                </div>

                <div v-func:role0009>
                  <el-dropdown-item key="4" @click="openRoleUserModel(row)">
                    <SvgIcon name="ele-Avatar" color="#d240ff"/>
                    <span style="padding-left: 5px; color: #d240ff">用户</span>
                  </el-dropdown-item>
                </div>

                <div v-func:role0023>
                  <el-dropdown-item key="5" @click="openAppMenuModel(row)">
                    <SvgIcon name="ele-Calendar" color="#409eff"/>
                    <span style="padding-left: 5px; color: #409eff">app菜单</span>
                  </el-dropdown-item>
                </div>

                <div v-func:flowLongDeploy015>
                  <el-dropdown-item key="6" @click="openFlowNodeModel(row)">
                    <SvgIcon name="ele-Calendar" color="#24997DFF"/>
                    <span style="padding-left: 5px; color: #24997DFF">流程节点授权</span>
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <zh-button v-func: link icon="" type="primary" @click="(row)"> </zh-button>
          <zh-button v-func: link icon="" type="primary" @click="(row)"> </zh-button>
          <zh-button v-func: link icon="" type="primary" @click="(row)"> </zh-button>
        </template>
      </zh-table>
    </zh-space>

    <zh-dialog :title="state.modalTitle" width="50%" v-model="state.visible" @confirm="saveRole">
      <role-form ref="rolePage" :roleInfo="state.selectRow" v-model="state.visible" />
    </zh-dialog>
    <zh-dialog title="用户授权" width="85%" v-model="state.roleUserVisible">
      <template v-slot:footer>
        <el-button @click="closeRoleUser"> 关闭 </el-button>
        <el-button type="primary" @click="saveUser" :disabled="state.saveUserDisable" v-if="!state.saveUserDisable"> 授权 </el-button>
        <el-button type="danger" @click="deleteUser" :disabled="state.deleteUserDisable" v-if="!state.deleteUserDisable"> 取消授权 </el-button>
      </template>
      <role-user-form ref="roleUserPage" @roleUserBtn="setRoleUserBtn" :roleInfo="state.selectRow" />
    </zh-dialog>
    <zh-dialog title="角色组织关联" width="80%" v-model="state.roleOrgVisible" @confirm="saveOrg">
      <template v-slot:footer v-if="state.activeNameOrg === 'list'">
        <el-button @click="closeOrg"> 关闭 </el-button>
        <el-button type="primary" @click="addOrg" :disabled="state.saveOrgDisable" v-if="!state.saveOrgDisable"> 关联 </el-button>
        <el-button type="danger" @click="deleteOrg" :disabled="state.deleteOrgDisable" v-if="!state.deleteOrgDisable"> 取消关联 </el-button>
      </template>
      <OrgModule
          ref="orgModelPage"
          @searchTypeBtn="setRoleOrgrBtn"
          @activeNameChange="activeNameChange"
          :id="state.roleId"
          v-model="state.roleOrgVisible"
          type="role"
      />
    </zh-dialog>
    <zh-dialog title="资源授权" width="40%" v-model="state.roleRouterFuncVisible" @confirm="saveRouterFunc">
      <router-func-tree-form ref="routerFuncTreePage" :roleId="state.roleId" v-model="state.roleRouterFuncVisible" type="role" />
    </zh-dialog>
    <zh-dialog title="app资源授权" width="40%" v-model="state.roleAppMenuVisible" @confirm="saveAppRouter">
      <app-menu-tree-form ref="appMenuTreePage" :roleId="state.roleId" v-model="state.roleAppMenuVisible" type="role" />
    </zh-dialog>
    <zh-dialog title="流程授权" width="450px" destroyOnClose v-model="state.flowNodeVisible" @confirm="saveFlowNode">
      <flow-node-tree-form ref="flowNodeTreePage" :roleId="state.roleId" v-model="state.flowNodeVisible" />
    </zh-dialog>
  </div>
</template>

<script lang="ts" setup name="roleManager">
import RoleForm from '@/views/system/config/role/component/RoleForm.vue';
import RoleUserForm from '@/views/system/config/role/component/RoleUserForm.vue';
import OrgModule from '@/views/system/component/OrgModule.vue';
import RouterFuncTreeForm from '@/views/system/user/component/RouterFuncTreeForm.vue';
import FlowNodeTreeForm from '@/views/system/user/component/FlowNodeTreeForm.vue';
import { ElMessageBox,ElMessage } from 'element-plus';
import AppMenuTreeForm from "@/views/system/user/component/AppMenuTreeForm.vue";

//------------------定义子组件---------------------------
const roleForm = ref<any>({});
const roleTable = ref<any>({});
const rolePage = ref<any>({});
const roleUserPage = ref<any>({});
const orgModelPage = ref<any>({});
const routerFuncTreePage = ref<any>({});
const flowNodeTreePage = ref<any>({});
const appMenuTreePage = ref<any>({});

//------------------内部变量定义-------------------------
const flagMap = {
  0: {
    status: 'error',
    text: '否',
  },
  1: {
    status: 'processing',
    text: '是',
  },
};
const state = reactive({
  description: '角色管理',
  dictData: {} as any,
  visible: false,
  form: null,
  mdl: {},

  // 高级搜索 展开/关闭
  advanced: false,
  // 查询参数
  queryParam: {} as any,
  // 表头
  loading: false,
  tablePage: {
    total: 0,
    currentPage: 1,
    pageNum: 1,
    pageSize: 20,
  },
  tableColumn: [
    { type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
    { field: 'roleId', title: '角色Id', fixed: 'left', visible: false, align: 'center', width: 150 },
    { field: 'roleName', title: '角色名称', align: 'center', fixed: 'left', width: 350 },
    {
      field: 'fixed',
      title: '是否可操作',
      align: 'center',
      width: 120,
      slots: {
        default: 'fixed_default',
      },
    },
    {
      field: 'status',
      title: '状态',
      align: 'center',
      editRender: {},
      slots: {
        // 使用插槽模板渲染
        default: 'status_edit',
        edit: 'status_edit',
      },
      width: 80,
    },
    { field: 'parentId', title: '父角色Id', visible: false, align: 'center', width: 200 },
    { field: 'roleType', title: '角色类型', visible: false, align: 'center', width: 100 },
    { field: 'roleTypeName', title: '角色类型', align: 'center', width: 150 },
    { field: 'createFullName', title: '创建人',  align: 'center', width: 300 },
    { field: 'appId', title: '应用id', visible: false, align: 'center', width: 100 },
    { field: 'appName', title: '所属应用', align: 'center', width: 300 },
    { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 300 },
    { field: 'operate', title: '操作', align: 'center', fixed: 'right', width: 300, slots: { default: 'operate_default' } },
  ],
  tableData: [],
  selectRow: null as any,
  modalTitle: '操作',
  roleUserVisible: false,
  saveUserDisable: false,
  deleteUserDisable: true,
  saveOrgDisable: false,
  deleteOrgDisable: true,
  roleOrgVisible: false,
  roleId: null as any,
  roleRouterFuncVisible: false,
  roleAppMenuVisible: false,
  flowNodeVisible: false,
  statusData: [
    { dictKey: '1', dictValue: '启用' },
    { dictKey: '0', dictValue: '禁用' },
  ],
  activeNameOrg: 'list',
});

//------------------定义调用方法-------------------------
function activeNameChange(name) {
  state.activeNameOrg = name;
}
function radioChangeEvent({ row }) {
  state.roleId = row.roleId;
  state.selectRow = row;
}
function clearRadioRowEevnt() {
  state.selectRow = null;
  roleTable.value.clearRadioRow();
}
function findRoleList() {
  roleTable.value.query(state.queryParam);
}
function refreshList() {
  roleTable.value.refresh(state.queryParam);
}
// 启用/禁用用户
function onStatusChange(row) {
  const params = {
    roleId: row.roleId,
    status: row.status,
  };
  let text = '禁用';
  if (params.status == '1') {
    text = '启用';
  }
  setTimeout(() => {
    $api.common.send
        .post('role0007', params)
        .then(() => {
          $messageBox.success(text + '成功', '提示');
        })
        .catch(() => {});
  }, 200);
}
function addRole() {
  clearRadioRowEevnt();
  state.modalTitle = '新增角色信息';
  state.visible = true;
}
function editRole(row) {
  if (row.fixed == '1') {
    if (row) {
      state.roleId=row.roleId
      state.selectRow = row;
      state.modalTitle = '修改角色信息';
      state.visible = true;
    } else {
      $messageBox.warning('请先选择需要修改的数据', '提示');
    }
  } else {
    $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
  }
}
function saveRole() {
  rolePage.value.saveRole().then((row) => {
    state.queryParam.roleName = row.roleName;
    findRoleList();
  });
}
function deleteRole(row) {
  if (row.fixed == '1') {
    if (row) {
      ElMessageBox.confirm('是否确认删除？').then(() => {
        const params = {
          roleId: row.roleId,
        };
        setTimeout(() => {
          $api.common.send
              .post('role0006', params)
              .then(() => {
                $messageBox.success('删除用户成功', '提示');
                refreshList();
              })
              .catch(() => {});
        }, 100);
      });

    } else {
      $messageBox.warning('请先选择需要删除的数据', '提示');
    }
  } else {
    $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
  }
}
function closeRoleUser() {
  state.roleUserVisible = false;
}
function openRoleUserModel(row) {
  // 打开添加用户页面
  if (row) {
    if (row.status === '0') {
      $messageBox.warning('该角色已禁用，不能操作', '提示');
      return;
    }
    state.selectRow = row;
    state.roleId = row.roleId;
    state.saveUserDisable = false;
    state.deleteUserDisable = true;
    state.roleUserVisible = true;
  } else {
    $messageBox.warning('请先选择需要操作的角色', '提示');
  }
}
function saveUser() {
  const roleId = state.selectRow.roleId;
  roleUserPage.value.saveUser(roleId);
}
function deleteUser() {
  roleUserPage.value.deleteUser(state.selectRow);
}

function setRoleUserBtn(value) {
  if (value) {
    if (value === '1') {
      state.saveUserDisable = false;
      state.deleteUserDisable = true;
    } else if (value === '2') {
      state.saveUserDisable = true;
      state.deleteUserDisable = false;
    }
    if (value === '3') {
      state.saveUserDisable = true;
      state.deleteUserDisable = true;
    }
  } else {
    state.saveUserDisable = false;
    state.deleteUserDisable = true;
  }
}
function setRoleOrgrBtn(value) {
  if (value) {
    if (value === '1') {
      state.saveOrgDisable = false;
      state.deleteOrgDisable = true;
    } else if (value === '2') {
      state.saveOrgDisable = true;
      state.deleteOrgDisable = false;
    }
    if (value === '3') {
      state.saveOrgDisable = true;
      state.deleteOrgDisable = true;
    }
  } else {
    state.saveOrgDisable = false;
    state.deleteOrgDisable = true;
  }
}
function openRoleOrgModel(row) {
  if (row) {
    if (row.status === '0') {
      $messageBox.warning('该角色已禁用，不能操作', '提示');
      return;
    }
    if (row.fixed !== '1') {
      $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
      return;
    }
    // 打开组织授权页面
    if (row.roleId) {
      state.roleId=row.roleId
      state.selectRow = row;
      state.roleOrgVisible = true;
    } else {
      $messageBox.warning('请先选择需要操作的角色', '提示');
    }
  } else {
    $messageBox.warning('请先选择需要操作的角色', '提示');
  }
}
function addOrg() {
  orgModelPage.value.add();
}
function saveOrg() {
  orgModelPage.value.save();
}
function deleteOrg() {
  orgModelPage.value.del();
}
function closeOrg() {
  state.roleOrgVisible = false;
}
function openRoleRouterFuncModel(row) {
  // 打开资源授权页面
  if (row.roleId) {
    if (row) {
      if (row.status === '0') {
        $messageBox.warning('该角色已禁用，不能操作', '提示');
        return;
      }
      if (row.fixed !== '1') {
        $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
        return;
      }
      state.roleId=row.roleId
      state.selectRow = row;
      state.roleRouterFuncVisible = true;
    } else {
      $messageBox.warning('请先选择需要操作的角色', '提示');
    }
  } else {
    $messageBox.warning('请先选择需要操作的角色', '提示');
  }
}
function openAppMenuModel(row) {
  // 打开资源授权页面
  if (row.roleId) {
    if (row) {
      if (row.status === '0') {
        $messageBox.warning('该角色已禁用，不能操作', '提示');
        return;
      }
      if (row.fixed !== '1') {
        $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
        return;
      }
      state.roleId=row.roleId
      state.selectRow = row;
      state.roleAppMenuVisible = true;
    } else {
      $messageBox.warning('请先选择需要操作的角色', '提示');
    }
  } else {
    $messageBox.warning('请先选择需要操作的角色', '提示');
  }
}
function saveAppRouter() {
  appMenuTreePage.value.saveAppRouter('role');
}
function saveRouterFunc() {
  routerFuncTreePage.value.saveRouterFunc('role');
}
function openFlowNodeModel(row) {
  if (row.roleId) {
    if (row) {
      if (row.status === '0') {
        $messageBox.warning('该角色已禁用，不能操作', '提示');
        return;
      }
      if (row.fixed !== '1') {
        $messageBox.warning('您没有修改该角色相关信息的权限', '提示');
        return;
      }
      // 打开资源授权页面
      state.roleId=row.roleId
      state.flowNodeVisible = true;
    } else {
      $messageBox.warning('请先选择需要操作的角色', '提示');
    }
  } else {
    $messageBox.warning('请先选择需要操作的角色', '提示');
  }
}
function saveFlowNode() {
  flowNodeTreePage.value.saveFlowNode('role');
}
function handleCurrentChange(row) {
  state.selectRow = row;
  state.roleId = row.roleId;
}

//------------------初始化------------------------------

// 数据字典初始化
const initDict = () => {
  const params = {
    dictFields: 'roleType',
  };
  $api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
  });
};

onMounted(() => {
  initDict();
  nextTick(() => {
    findRoleList();
  });
});
</script>
<style lang="scss" scoped></style>